package com.isyscore.os.metadata.service.impl;

import com.google.common.base.Strings;
import com.isyscore.boot.quartz.QuartzTemplate;
import com.isyscore.os.core.exception.DataFactoryException;
import com.isyscore.os.core.exception.ErrorCode;
import com.isyscore.os.core.util.InitiallyUtils;
import com.isyscore.os.metadata.manager.QuartzJobManager;
import com.isyscore.os.metadata.model.entity.Metric;
import com.isyscore.os.metadata.service.quartz.MetricJobTask;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.isyscore.os.metadata.constant.CommonConstant.METRIC_CALCULATE_JOB_GROUP;

/**
 * <p>
 * 指标的定时计算任务信息 服务实现类
 * </p>
 *
 * @author
 * @since 2021-08-11
 */
@Service
public class MetricJobService {

    @Autowired
    private MetricService metricService;

    @Autowired
    private QuartzJobManager quartzJobManager;

    @Autowired
    private QuartzTemplate quartzTemplate;

    /**
     * 更新指标的JOB配置信息
     */
    public void refreshMetricJob(Long metricId, String cron) {
        Metric metric = metricService.getMetricById(metricId);
        if (Strings.isNullOrEmpty(cron)) {
            metric.setTaskCron("");
            quartzJobManager.deleteJob(metricId,METRIC_CALCULATE_JOB_GROUP);
            metricService.updateById(metric);
        } else {
            if (!CronExpression.isValidExpression(cron)) {
                throw new DataFactoryException(ErrorCode.METRIC_JOB_CRON_INVALID);
            }
            metric.setTaskCron(cron);
            if (quartzJobManager.hasTask(metricId,METRIC_CALCULATE_JOB_GROUP)) {
                quartzJobManager.deleteJob(metricId,METRIC_CALCULATE_JOB_GROUP);
            }
            quartzJobManager.addJob(metricId, cron,METRIC_CALCULATE_JOB_GROUP, MetricJobTask.class);
            metricService.updateById(metric);
        }
    }


    public void deleteMetricJob(Long metricId) {
        Metric metric = metricService.getMetricById(metricId);
        metric.setTaskCron("");
        metricService.updateById(metric);
        quartzJobManager.deleteJob(metricId,METRIC_CALCULATE_JOB_GROUP);
    }

    public void startAllMetricJobFromDatabase() {
        List<Metric> metrics = InitiallyUtils.markInitially(() -> metricService.getAllMetricWithJobInfo());
        for (Metric metric : metrics) {
            //添加数据库中已存在的定时计算任务
            if (!Strings.isNullOrEmpty(metric.getTaskCron())) {
                quartzJobManager.addJob(metric.getId(), metric.getTaskCron(),METRIC_CALCULATE_JOB_GROUP, MetricJobTask.class);
            }
        }
    }

}
